package com.ophiux.cs.application.consultBase.impl;

import com.ophiux.cs.application.consultBase.dto.AddDoctorRequest;
import com.ophiux.cs.application.consultBase.dto.AddDoctorResponse;
import com.ophiux.cs.application.consultBase.service.IAddDoctorAppService;
import com.ophiux.cs.application.core.AppResultCode;
import com.ophiux.cs.application.core.Result;
import com.ophiux.cs.application.core.ResultEnum;
import com.ophiux.cs.domain.consultBase.model.entity.Doctor;
import com.ophiux.cs.domain.consultBase.repositories.IDoctorRepository;
import com.ophiux.utils.common.RandomUtil;
import com.ophiux.utils.common.ShiftUtils;
import com.ophiux.utils.exception.OphiuxRepositoryException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AddDoctorAppService implements IAddDoctorAppService {

    @Autowired
    IDoctorRepository doctorRepositories;

    @Override
    public Result<AddDoctorResponse> createDoctor(AddDoctorRequest dto) {
        AddDoctorResponse resp = new AddDoctorResponse();
        //验证参数是否允许为空
        if (!dto.isParamValid()) {
            return Result.fail(ResultEnum.requestParamFail.getCode(), ResultEnum.requestParamFail.getMsg());
        }
        try {
            Doctor doc = null;
            doc = (Doctor) ShiftUtils.objToNewObj(dto, Doctor.class);
            try {
                boolean flag=true;
                String docID="";
                //生成医生编码
                while(flag){
                    //随机生成8位数
                    docID= RandomUtil.getRandomNum(8);
                    Doctor doc1=doctorRepositories.getDoctorByID(docID);
                    if(doc1==null){
                        doc.setDOCTOR_ID(docID);
                        flag=false;
                    }
                }
                //新增医生
                doctorRepositories.createDoctor(doc);
                resp.setDOCTOR_ID(doc.getDOCTOR_ID());
            } catch (OphiuxRepositoryException e) {
                e.printStackTrace();
                return Result.fail(ResultEnum.requestException.getCode(), e.getExceptionMessage());
            }
        } catch (Exception e) {
            log.info("createHospital接口异常：", e);
            e.printStackTrace();
            return Result.fail(AppResultCode.EXCEPTION, "程序异常");
        }
        return Result.success(resp, "新增医生成功");
    }

}
